<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  <title>tracking.js - face tracking fish tank</title>
  <link rel="stylesheet" href="assets/demo.css">

  <script src="../build/tracking-min.js"></script>
  <script src="../build/data/face-min.js"></script>
  <script src="../../threejs/build/three.min.js"></script>
  <script src="assets/fish_tank/FishTankRenderer.js"></script>

  <style>
  body {
    overflow: hidden;
  }

  #video, #canvas {
    bottom: 0;
    position: absolute;
    z-index: 100;
  }

  #viewport {
    padding-top: 40px;
  }
  </style>
</head>

<body>
  <div class="demo-title">
    <p><a href="http://trackingjs.com" target="_parent">tracking.js</a> － get user's webcam and detect faces to control the scene</p>
  </div>

  <div id="viewport">
    <video id="video" width="320" height="240" preload autoplay loop muted></video>
    <canvas id="canvas" width="320" height="240"></canvas>
  </div>

  <script>
    var viewport = document.getElementById('viewport');
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    var fishTankRenderer = new FishTankRenderer();
    fishTankRenderer.init(viewport);

    var faceX = 0;
    var faceY = 0;

    var tracker = new tracking.ObjectTracker('face');
    tracker.setInitialScale(4);
    tracker.setStepSize(2);

    tracking.track('#video', tracker, { camera: true });

    tracker.on('track', function(event) {
      var maxRectArea = 0;
      var maxRect;

      event.data.forEach(function(rect) {
        if (rect.width * rect.height > maxRectArea){
          maxRectArea = rect.width * rect.height;
          maxRect = rect;
        }

        context.clearRect(0, 0, canvas.width, canvas.height);
        context.strokeStyle = 'magenta';
        context.strokeRect(rect.x, rect.y, rect.width, rect.height);
        context.font = '11px Helvetica';
        context.fillStyle = "#fff";
        context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
        context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
      });

      if(maxRectArea > 0) {
        var rectCenterX = maxRect.x + (maxRect.width/2);
        var rectCenterY = maxRect.y + (maxRect.height/2);
        faceX = (rectCenterX - 160) * (window.innerWidth/320) * 50;
        faceY = (rectCenterY - 120) * (window.innerHeight/240) * 50;
      }

      fishTankRenderer.render(faceX, faceY);
    });
  </script>

</body>
</html>
